const express = require("express");
const router = express.Router();
const db = require("../config/database");
const { body, validationResult } = require("express-validator");
const {
  authenticateToken,
  generateString,
  encryptPhone,
  decryptPhone,
  extractNumber,
  getNextId,
  logUserOperation,
} = require("../untils/untils");
const dayjs = require("dayjs");
const { cryptoHelper } = require("../config/global");
const openAI = require("../utils/openAI");

// 获取商机列表
//参数: oppo_id=&emp_id=&cust_id=&stage=%E8%B5%A2%E5%8D%95
router.get("/", authenticateToken, async (req, res) => {
  try {
    const { oppo_id, emp_id, cust_id, stage } = req.query;
    let sql = "SELECT * FROM business_opportunity WHERE 1=1";
    if (oppo_id) {
      sql += ` AND oppo_id = '${oppo_id}'`;
    }
    if (emp_id) {
      sql += ` AND emp_id = '${emp_id}'`;
    }
    if (cust_id) {
      sql += ` AND cust_id = '${cust_id}'`;
    }
    if (stage) {
      sql += ` AND stage = '${stage}'`;
    }

    let [result] = await db.execute(sql);

    // // 获取客户信息
    const [cust_info] = await db.execute("SELECT * FROM customer");

    // // 获取员工信息
    // const [emp_info] = await db.execute('SELECT * FROM employee WHERE emp_id IN (?)', result.map(item => item.emp_id));
    // const [emp_info] = await db.execute('SELECT * FROM employee WHERE emp_id IN (?)', result.map(item => item.emp_id));
    const [emp_info] = await db.execute("SELECT * FROM employee");

    result.forEach(async (item) => {
      // 把所有日期类型的全部格式化成YYYY-MM-DD HH:mm:ss
      if (dayjs(item.contact_date).isValid()) {
        item.contact_date = dayjs(item.contact_date).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      if (dayjs(item.create_time).isValid()) {
        item.create_time = dayjs(item.create_time).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      // 获取客户信息
      item.cust_name = cust_info.find((cust) => cust.cust_id === item.cust_id)
        ? cust_info.find((cust) => cust.cust_id === item.cust_id).cust_name
        : item.cust_id;
      item.emp_name = emp_info.find((emp) => emp.emp_id === item.emp_id)
        ? emp_info.find((emp) => emp.emp_id === item.emp_id).emp_name
        : item.emp_id;
    });

    await logUserOperation(
      req,
      "查询",
      "获取商机列表",
      "获取商机列表成功",
      "成功"
    );
    res.json({
      success: true,
      data: result,
    });
  } catch (error) {
    console.error("获取商机列表失败:", error);
    await logUserOperation(
      req,
      "查询",
      "获取商机列表",
      "获取商机列表失败",
      "失败",
      error.message
    );
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// 新增商机
// { "emp_id": "MG00001", "cust_id": "C00001", "demand_desc": "123", "stage": "待接触" }
router.put("/add", authenticateToken, async (req, res) => {
  try {
    let {
      cust_id,
      emp_id,
      contact_date,
      demand_desc,
      stage,
      lost_reason,
      lost_notes,
      demand_summary,
    } = req.body;

    // 商机编码
    const oppo_id = await getNextId("BO", "oppo_id", "business_opportunity", 5);

    const create_time = dayjs().format("YYYY-MM-DD HH:mm:ss");

    // // 判断需求描述是否为空
    // if (!(demand_desc == '' || demand_desc == null || demand_desc == undefined)) {
    //     openAI.business_opportunity(demand_desc, oppo_id);
    // }

    if (!contact_date) {
      contact_date = null;
    }

    const sql = `INSERT INTO business_opportunity (oppo_id, cust_id, emp_id, contact_date, demand_desc, stage, lost_reason, lost_notes, create_time, demand_summary) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
    const params = [
      oppo_id,
      cust_id,
      emp_id,
      contact_date,
      demand_desc,
      stage,
      lost_reason,
      lost_notes,
      create_time,
      demand_summary
    ];
    await db.execute(sql, params);
    await logUserOperation(req, "添加", "新增商机", "新增商机成功", "成功");
    res.json({
      success: true,
      message: "新增商机成功",
    });
  } catch (error) {
    console.error("新增商机失败:", error);
    await logUserOperation(
      req,
      "添加",
      "新增商机",
      "新增商机失败",
      "失败",
      error.message
    );
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// 编辑商机
router.post("/update", authenticateToken, async (req, res) => {
  try {
    let {
      oppo_id,
      cust_id,
      emp_id,
      contact_date,
      demand_desc,
      stage,
      lost_reason,
      lost_notes,
    } = req.body;

    // 判断需求描述是否变化或者为空  如果为空则不进行需求总结
    // 如果需求描述未变化则不进行需求总结
    // 如果需求描述为空则不进行需求总结
    // 如果需求变化调用openAI生成需求总结
    // let demand_summary = ''
    // const [result] = await db.execute(`SELECT demand_desc FROM business_opportunity WHERE oppo_id = ?`, [oppo_id]);
    // if (result.length > 0) {
    //     if (result[0].demand_desc == '' || result[0].demand_desc == null || result[0].demand_desc == undefined) {
    //         demand_summary = ''
    //     } else if (result[0].demand_desc == demand_desc) {
    //         demand_summary = result[0].demand_summary
    //     } else {
    //         demand_summary = await openAI.business_opportunity(demand_desc);
    //         // 去掉需求总结中的“- 需求总结:”
    //         demand_summary = demand_summary.replace('- 需求总结:', '');
    //     }
    // } else {
    //     // 判断需求描述是否为空
    //     if (demand_desc == '' || demand_desc == null || demand_desc == undefined) {
    //         demand_summary = ''
    //     } else {
    //         demand_summary = await openAI.business_opportunity(demand_desc);
    //         // 去掉需求总结中的“- 需求总结:”
    //         demand_summary = demand_summary.replace('- 需求总结:', '');
    //     }
    // }

    const sql = `UPDATE business_opportunity SET cust_id = ?, emp_id = ?, contact_date = ?, demand_desc = ?, stage = ?, lost_reason = ?, lost_notes = ? WHERE oppo_id = ?`;
    const params = [
      cust_id,
      emp_id,
      contact_date,
      demand_desc,
      stage,
      lost_reason,
      lost_notes,
      oppo_id,
    ];

    // 更新商机
    await db.execute(sql, params);
    await logUserOperation(req, "更新", "更新商机", "更新商机成功", "成功");
    res.json({
      success: true,
      message: "编辑商机成功",
    });
  } catch (error) {
    console.error("编辑商机失败:", error);
    await logUserOperation(
      req,
      "更新",
      "更新商机",
      "更新商机失败",
      "失败",
      error.message
    );
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// 删除商机
router.delete("/delete", authenticateToken, async (req, res) => {
  try {
    const { oppo_id } = req.query;
    const sql = `DELETE FROM business_opportunity WHERE oppo_id = ?`;
    await db.execute(sql, [oppo_id]);
    await logUserOperation(req, "删除", "删除商机", "删除商机成功", "成功");
    res.json({
      success: true,
      message: "删除商机成功",
    });
  } catch (error) {
    console.error("删除商机失败:", error);
    await logUserOperation(
      req,
      "删除",
      "删除商机",
      "删除商机失败",
      "失败",
      error.message
    );
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// 获取商机阶段
// 待接触/初步提议/方案询价/协商议价/赢单/丢失客户
router.get("/stage", authenticateToken, async (req, res) => {
  try {
    const stage = [
      { key: "待接触", name: "待接触" },
      { key: "初步提议", name: "初步提议" },
      { key: "方案询价", name: "方案询价" },
      { key: "协商议价", name: "协商议价" },
      { key: "赢单", name: "赢单" },
      { key: "丢失客户", name: "丢失客户" },
    ];
    res.json({
      success: true,
      data: stage,
    });
  } catch (error) {
    console.error("获取商机阶段失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// 获取查询项销售人员
router.get("/emp", authenticateToken, async (req, res) => {
  try {
    const [result] = await db.execute(
      `SELECT DISTINCT employee.emp_id as 'key', employee.emp_name as 'name' FROM employee JOIN business_opportunity ON employee.emp_id = business_opportunity.emp_id`
    );
    res.json({
      success: true,
      data: result,
    });
  } catch (error) {
    console.error("获取查询项销售人员失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// 获取查询项客户
router.get("/cust", authenticateToken, async (req, res) => {
  try {
    const [result] = await db.execute(
      `SELECT DISTINCT customer.cust_id as 'key', customer.cust_name as 'name' FROM customer JOIN business_opportunity ON customer.cust_id = business_opportunity.cust_id`
    );
    res.json({
      success: true,
      data: result,
    });
  } catch (error) {
    console.error("获取查询项客户失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

// AI 生成商机需求总结
router.post("/summary", authenticateToken, async (req, res) => {
  try {
    const { oppo_id, demand_desc } = req.body;
    const summary = await openAI.business_opportunity(demand_desc);
    res.json({
      success: true,
      data: summary,
    });
  } catch (error) {
    console.error("AI 生成商机需求总结失败:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
    });
  }
});

module.exports = router;
